const express = require('express');
const mysql = require('mysql2/promise');
const bcrypt = require('bcrypt');
const multer = require('multer');
const path = require('path');
const cors = require('cors');

const app = express();
const PORT = 3000;

// 中间件
app.use(cors());
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

// 文件上传配置

const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, 'uploads/');
  },
  filename: function (req, file, cb) {
    cb(null, Date.now() + path.extname(file.originalname));
  }
});

const upload = multer({ storage: storage });


// MySQL数据库连接配置
const dbConfig = {
  host: 'localhost',
  user: '',
  password: '',
  database: 'mental_health_app',
  port: 3306
};

// 创建数据库连接池
const pool = mysql.createPool(dbConfig);

// 初始化数据库表
async function initDatabase() {
  try {
    const connection = await pool.getConnection();
    
    // 创建用户表
    await connection.execute(`
      CREATE TABLE IF NOT EXISTS users (
        id INT AUTO_INCREMENT PRIMARY KEY,
        nickname VARCHAR(50) NOT NULL,
        email VARCHAR(100) UNIQUE NOT NULL,
        password VARCHAR(255) NOT NULL,
        gender ENUM('male', 'female') NOT NULL,
        avatar VARCHAR(255),
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
      )
    `);

    // 创建聊天记录表
    await connection.execute(`
      CREATE TABLE IF NOT EXISTS chat_messages (
        id INT AUTO_INCREMENT PRIMARY KEY,
        user_id INT NOT NULL,
        content TEXT NOT NULL,
        is_user BOOLEAN NOT NULL,
        timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        FOREIGN KEY (user_id) REFERENCES users(id)
      )
    `);

    connection.release();
    console.log('数据库表初始化完成');
  } catch (error) {
    console.error('数据库初始化失败:', error);
  }
}

// 用户注册API
app.post('/api/register', async (req, res) => {
  try {
    const { nickname, email, password, gender } = req.body;

    // 验证必填字段
    if (!nickname || !email || !password || !gender) {
      return res.status(400).json({
        code: 400,
        message: '请填写所有必填字段',
        data: null
      });
    }

    // 验证邮箱格式
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    if (!emailRegex.test(email)) {
      return res.status(400).json({
        code: 400,
        message: '邮箱格式不正确',
        data: null
      });
    }

    // 验证密码长度
    if (password.length < 6) {
      return res.status(400).json({
        code: 400,
        message: '密码长度至少6位',
        data: null
      });
    }

    const connection = await pool.getConnection();

    // 检查邮箱是否已存在
    const [existingUsers] = await connection.execute(
      'SELECT id FROM users WHERE email = ?',
      [email]
    );

    if (existingUsers.length > 0) {
      connection.release();
      return res.status(400).json({
        code: 400,
        message: '该邮箱已被注册',
        data: null
      });
    }

    // 加密密码
    const hashedPassword = await bcrypt.hash(password, 10);

    // 插入新用户
    const [result] = await connection.execute(
      'INSERT INTO users (nickname, email, password, gender) VALUES (?, ?, ?, ?)',
      [nickname, email, hashedPassword, gender]
    );

    connection.release();

    res.json({
      code: 200,
      message: '注册成功',
      data: {
        userId: result.insertId,
        nickname,
        email,
        gender
      }
    });

  } catch (error) {
    console.error('注册失败:', error);
    res.status(500).json({
      code: 500,
      message: '服务器内部错误',
      data: null
    });
  }
});

// 用户登录API
app.post('/api/login', async (req, res) => {
  try {
    const { email, password } = req.body;

    if (!email || !password) {
      return res.status(400).json({
        code: 400,
        message: '请填写邮箱和密码',
        data: null
      });
    }

    const connection = await pool.getConnection();

    // 查找用户
    const [users] = await connection.execute(
      'SELECT * FROM users WHERE email = ?',
      [email]
    );

    if (users.length === 0) {
      connection.release();
      return res.status(401).json({
        code: 401,
        message: '用户不存在',
        data: null
      });
    }

    const user = users[0];

    // 验证密码
    const isPasswordValid = await bcrypt.compare(password, user.password);

    if (!isPasswordValid) {
      connection.release();
      return res.status(401).json({
        code: 401,
        message: '密码错误',
        data: null
      });
    }

    connection.release();

    res.json({
      code: 200,
      message: '登录成功',
      data: {
        userId: user.id,
        nickname: user.nickname,
        email: user.email,
        gender: user.gender,
        avatar: user.avatar
      }
    });

  } catch (error) {
    console.error('登录失败:', error);
    res.status(500).json({
      code: 500,
      message: '服务器内部错误',
      data: null
    });
  }
});

// 获取用户信息API
app.get('/api/user/:userId', async (req, res) => {
  try {
    const { userId } = req.params;

    if (!userId) {
      return res.status(400).json({
        code: 400,
        message: '用户ID不能为空',
        data: null
      });
    }

    const connection = await pool.getConnection();

    // 查询用户信息
    const [users] = await connection.execute(
      'SELECT id, nickname, email, gender, avatar, created_at FROM users WHERE id = ?',
      [userId]
    );

    if (users.length === 0) {
      connection.release();
      return res.status(404).json({
        code: 404,
        message: '用户不存在',
        data: null
      });
    }

    const user = users[0];
    connection.release();

    res.json({
      code: 200,
      message: '获取用户信息成功',
      data: {
        userId: user.id,
        nickname: user.nickname,
        email: user.email,
        gender: user.gender,
        avatar: user.avatar,
        createdAt: user.created_at
      }
    });

  } catch (error) {
    console.error('获取用户信息失败:', error);
    res.status(500).json({
      code: 500,
      message: '服务器内部错误',
      data: null
    });
  }
});

// 头像上传API
app.post('/api/upload-avatar', upload.single('image'), async (req, res) => {
  try {
    const { userID } = req.body;
    const avatarUrl = req.file ? `/uploads/${req.file.filename}` : null;

    if (!avatarUrl) {
      return res.status(400).json({
        code: 400,
        message: '上传文件失败',
        data: null
      });
    }

    const connection = await pool.getConnection();

    // 更新用户头像
    await connection.execute(
      'UPDATE users SET avatar = ? WHERE id = ?',
      [avatarUrl, userID]
    );

    connection.release();

    res.json({
      code: 200,
      message: '头像上传成功',
      data: {
        url: avatarUrl,
        userID: userID
      }
    });

  } catch (error) {
    console.error('头像上传失败:', error);
    res.status(500).json({
      code: 500,
      message: '服务器内部错误',
      data: null
    });
  }
});
// 启动服务器
app.listen(PORT, async () => {
  console.log(`服务器运行在 http://localhost:${PORT}`);
  await initDatabase();
}); 